#!/usr/local/bin/python3
#--coding:utf-8--

from http.server import BaseHTTPRequestHandler,HTTPServer,SimpleHTTPRequestHandler
import qrcode
import socket
import webbrowser

# ↓↓↓ 在下方  修改发布的文件夹路径  config directory below

#配置路径 
target_dir="/Users/lucas/files/"

# ↑↑↑ 在上方  修改发布的文件夹路径 config directory above 

# --------以下莫动----DO NOT CHANGE BELOW-------------


#获取本机电脑名
myname = socket.getfqdn(socket.gethostname())

#获取本机ip
ipaddr = socket.gethostbyname(myname)

# 设定端口
port = 8000

#访问路径
path="http://"+ipaddr+":"+str(port)

# 定制
class MyHttpRequestHandler(SimpleHTTPRequestHandler):
	def __init__(self, *args, directory=None, **kwargs):
		super().__init__( *args, directory=target_dir, **kwargs)

 
def run():
	print('starting server, port', port)

	# Server settings
	server_address = ('', port)
	# TODO 修改发布的路径
	httpd = HTTPServer(server_address, MyHttpRequestHandler)
	print('running server...')
	httpd.serve_forever()

def generateQr():
	qr = qrcode.QRCode(
		version=1,
		error_correction=qrcode.constants.ERROR_CORRECT_L,
		box_size=10,
		border=4,
	)
	print("写入到文件的路径为:"+path)
	qr.add_data(path)
	qr.make(fit=True)

	img = qr.make_image(fill_color="black", back_color="white")
	img.save(target_dir+"site.png")

def generateHtml():
	generateQr()
	index_file_name='site.html'
	index_html='''
	<html>
		<head>
		<title>Welcome! 欢迎您访问</title>
		<meta charset='utf-8'/>
		</head>
		<body>
			<h2>Scan the QRCode below to visit</h2>
			<h2>请扫描下面的二维码打开网站</h2>
			<h3>或者直接访问 direct visit : <a href='{}'>{}</a></h3>
			<img src='{}/site.png'/>
		</body>
	</html>
	'''.format(path,path,path)
	my_open = open(target_dir+index_file_name, 'w+')
	my_open.write(index_html)
	my_open.close()

def openSite():
	generateHtml()
	webbrowser.open(path+'/site.html')

if __name__ == '__main__':
	# MyHttpRequestHandler()
	openSite()
	run()